import { getEntityList } from '../base'
import { RefIndex } from '../util/ref-index'
import { SegmentItemIndex } from '../util/segment'
import { WaypointSegmentIndex, makeRouteSegmentIndex } from '../util/waypoint-segment'
import type { Waypoint } from '../waypoint'
import type { ATSRoute } from './types'

export let atsRouteIndex: SegmentItemIndex<ATSRoute>
export let atsRouteSegmentIndex: WaypointSegmentIndex<ATSRoute>

export function initATSRouteIndex(lst: ATSRoute[]) {
  atsRouteSegmentIndex = makeRouteSegmentIndex(lst)
  atsRouteIndex = new SegmentItemIndex(atsRouteSegmentIndex.segments())
}

let atsRouteByWaypoint: RefIndex<Waypoint, ATSRoute>
export function getWaypointATSRouteSet(wpt: string): Set<ATSRoute> | undefined {
  let s = atsRouteByWaypoint
  if (!s) {
    s = new RefIndex<Waypoint, ATSRoute>(getEntityList<ATSRoute>('ATSRoute'), (r) => {
      return r.waypointList
    })
    atsRouteByWaypoint = s
  }
  return s.get(wpt)
}
